package com.yuntian.controller.user;


import com.yuntian.Vo.user.UserLoginVo;
import com.yuntian.entity.User;
import com.yuntian.properties.JwtProperties;
import com.yuntian.result.Result;
import com.yuntian.service.UserService;
import com.yuntian.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController("UserUserController")
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody User user){
        User login = userService.login(user);
        if(login == null){
            return Result.error("登录失败，用户名或密码错误");
        }
        //生成jwt令牌
        Map<String,Object> claims = new HashMap() ;
        claims.put("userId",login.getUserId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        return Result.success(
                UserLoginVo.builder()
                        .userId(login.getUserId())
                        .username(login.getUsername())
                        .token(token)
                        .build()
        );
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        userService.register(user);
        return Result.success();
    }
}
